﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ZiChen.SoXunLeiPan.Common
{
    public static class UrlSignTopRequest
    {
        /// <summary>
        /// 参数加密
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="secret"></param>
        /// <param name="signMethod"></param>
        /// <returns></returns>
        public static string Sign(Dictionary<string, object> parameters, string secret)
        {
            // 第一步：把字典按Key的字母顺序排序
            IDictionary<string, object> sortedParams = new SortedDictionary<string, object>(parameters, StringComparer.Ordinal);
            List<string> list = new();
            // 第二步：把所有参数名和参数值串在一起
            foreach (KeyValuePair<string, object> kv in sortedParams)
            {
                if (kv.Key != "sign")//sign不参与排序
                {
                    list.Add(kv.Key);
                    list.Add(kv.Value?.ToString());
                }
            }
            list.Add(secret);
            list.Sort(StringComparer.Ordinal);
            string joinStr = string.Join("-", list);
            // 第三步：使用Aes加密
            return Encrypt(joinStr, secret);
        }
        public static string Encrypt(string plainText, string key)
        {
            if (string.IsNullOrEmpty(plainText))
                return string.Empty;

            byte[] encrypted;

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(key);
                aesAlg.IV = new byte[16];

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using MemoryStream msEncrypt = new();
                using CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write);
                using (StreamWriter swEncrypt = new(csEncrypt))
                {
                    swEncrypt.Write(plainText);
                }
                encrypted = msEncrypt.ToArray();
            }

            return Convert.ToBase64String(encrypted);
        }
    }
}
